#include "es_print.h"
#include "ahumqtt.h"
#include <unistd.h>
#include "ahudata.h"
#include "ahufsm.h"
#include "ahuprotocal.h"
#include "ahutimer.h"
#include "ahupid.h"
#include "ahuproc.h"

extern struct mosquitto *mqtt_ahu;
extern bool clean_session;
extern bool unclean_session;

pthread_t tid_state_ck = -1;
pthread_t tid_protocal = -1;
pthread_t tid_tm = -1;
pthread_t tid_hmdt = -1;
pthread_t tid_temp = -1;
pthread_t tid_rt = -1;

/* 空调设备头节点，所有的空调都链接在这个头后面 */
ahu_dev_t *ahu_dev_hd;

/* 消息队列使用 */
key_t mkey;
int	mq_id = -1;	// 用于接收事件

/* 定时器线程使用 */
sigset_t tt_set;

/* 定时用的 */
struct itimerval to_sigprop = {
    {0, 0},
    {1, 0}
};

int main(int argc, const char *argv[])
{
	/* 空调设备链表头 */
	ahu_dev_hd = malloc(sizeof(ahu_dev_t)*1);

	INIT_LIST_HEAD(&ahu_dev_hd->list);

	pthread_mutex_init(&ahu_dev_hd->lock, NULL);

	/* 消息队列初始化 */
	mkey = ftok("/bin/ls", 1);
	mq_id = msgget(mkey, 0600|IPC_CREAT);
	ES_PRT_INFO("Cpo create message queue, mq_id = %d \n", mq_id);
	if(mq_id < 0){
		ES_PRT_ERROR("%s \n", strerror(errno));
		exit(1);
	}

	/* 定时器线程使用, 阻塞接收alarm信号 */
	sigemptyset(&tt_set);
	sigaddset(&tt_set, SIGALRM);
    pthread_sigmask(SIG_BLOCK, &tt_set, NULL);

	/* mqtt */
	mosquitto_lib_init();
	mqtt_ahu = mosquitto_new(NULL, clean_session, NULL);
	if(!mqtt_ahu){
        ES_PRT_ERROR("create mqtt client failed.. \n");
		goto mqttclean;
    }

	mosquitto_subscribe_callback_set(mqtt_ahu, ahu_mqtt_sub_cb);
	mosquitto_connect_callback_set(mqtt_ahu, ahu_mqtt_conn_cb);
	mosquitto_message_callback_set(mqtt_ahu, ahu_mqtt_msg_cb);
//	mosquitto_log_callback_set(mosq, AirCondLogCb);

	if(MOSQ_ERR_SUCCESS != mosquitto_connect(mqtt_ahu, ES_MQTT_HOST, ES_MQTT_PORT, ES_MQTT_KEEPALIVE)){
		perror("Unable to connect.\n");
		goto mqttdestroy;
		return 1;
	}
	mosquitto_loop_start(mqtt_ahu);

	/* 2 订阅 */
	mosquitto_subscribe(mqtt_ahu, NULL, MQTT_SUB_INIT_CMD, 0);

	/* timer thread */
	pthread_create(&tid_tm, NULL, es_timer_thread, &tt_set);

	/* 轮询检查和状态相关的点位, 根据不同情况发送不同事件 */
	pthread_create(&tid_state_ck, NULL, ahu_state_ck_thread, NULL);

	/* msgrcv接收信息，然后分类处理 */
	pthread_create(&tid_protocal, NULL, ahu_event_thread, NULL);

	/* 湿控 */
	pthread_create(&tid_hmdt, NULL, ahu_hmdt_ctl_thread, NULL);

	/* 温控 */
	pthread_create(&tid_temp, NULL, ahu_temp_ctl_thread, NULL);

	/* 运行时数据更新 */
	pthread_create(&tid_rt, NULL, ahu_rt_update_thread, NULL);

	/* 读取本地配置目录，添加设备 */
	add_dev_from_local();

	pause();
	return 0;

mqttdestroy:
	mosquitto_destroy(mqtt_ahu);
mqttclean:
	mosquitto_lib_cleanup();

	return 1;
}